<?php

namespace app\admin\controller\admin;

use app\common\controller\AdminController;
use app\common\services\annotation\ControllerAnnotation;
use app\common\services\annotation\NodeAnnotation;
use Juhelib\excel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use support\Request;
use support\Response;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="payment_activity_prize")
 */
class PaymentActivityPrizeController extends AdminController
{

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\PaymentActivityPrize();
    }

    /**
     * @NodeAnnotation(title="列表")
     */
    public function index(Request $request): Response
    {
        list($page, $limit, $where) = $this->buildTableParams();

        $activity_id = $request->get('activity_id');
        if (!empty($activity_id)) {
            $where[] = ['a.activity_id', '=', $activity_id];
        }
        $user_id = $request->get('user_id');
        if (!empty($user_id)) {
            $where[] = ['a.user_id', '=', $user_id];
        }
        if (!$request->isAjax()) {
            return $this->fetch('', ['activityId' => $activity_id ?? '', 'userId' => $user_id ?? '']);
        }
        if ($request->input('selectFields')) {
            return $this->selectList();
        }

        $count = $this->model
            ->alias('a')
            ->join('user b', 'a.user_id = b.id', 'left')
            ->join('activity d', 'a.activity_id = d.id', 'left')
            ->join('user c', 'd.user_id = c.id', 'left')
            ->join('activity_prize e', 'a.activity_prize_id = e.id', 'left')
            ->join('order o', 'a.order_id = o.id', 'left')
            ->field('a.*, b.nickname, b.openid, c.nickname as staff_nickname, d.activity_title')
            ->where($where ?? [])
            ->count();
        $list = $this->model
            ->alias('a')
            ->join('user b', 'a.user_id = b.id', 'left')
            ->join('activity d', 'a.activity_id = d.id', 'left')
            ->join('user c', 'd.user_id = c.id', 'left')
            ->join('activity_prize e', 'a.activity_prize_id = e.id', 'left')
            ->join('order o', 'a.order_id = o.id', 'left')
            ->field('a.*, b.nickname, b.openid, c.nickname as staff_nickname, d.activity_title')
            ->where($where ?? [])
            ->order($this->order)->page($page, $limit)->select()->toArray();
        foreach ($list as &$value) {
            $value['order_info'] = Db::name('order')->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id']])->field('name, phone, customer_type')->find();
        }
        $data  = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

    /**
     * @NodeAnnotation(title="核销")
     */
    public function prizeConfirm(Request $request): Response
    {
        $id  = (int)$request->input('id');
        $this->model->where(['id' => $id])->update(['status' => 2]);
        return $this->success('核销成功');
    }

    /**
     * @NodeAnnotation(title="作废")
     */
    public function prizeCancel(Request $request): Response
    {
        $id  = (int)$request->input('id');
        $this->model->where(['id' => $id])->update(['status' => 1]);
        return $this->success('作废成功');
    }

    /**
     * @NodeAnnotation(title="导出")
     */
    public function export(Request $request): Response|bool
    {
        try {
            list($page, $limit, $where) = $this->buildTableParams();

            $activity_id = $request->get('activity_id');
            if (!empty($activity_id)) {
                $where[] = ['a.activity_id', '=', $activity_id];
            }
            $user_id = $request->get('user_id');
            if (!empty($user_id)) {
                $where[] = ['a.user_id', '=', $user_id];
            }

            $list = $this->model
                ->alias('a')
                ->join('user b', 'a.user_id = b.id', 'left')
                ->join('activity d', 'a.activity_id = d.id', 'left')
                ->join('user c', 'd.user_id = c.id', 'left')
                ->join('activity_prize e', 'a.activity_prize_id = e.id', 'left')
                ->join('order o', 'a.order_id = o.id', 'left')
                ->field('a.*, b.nickname, b.openid, c.nickname as staff_nickname, d.activity_title')
                ->where($where ?? [])
                ->order($this->order)->select()->toArray();
            foreach ($list as $key => $value) {
                $value['order_info'] = Db::name('order')->where(['activity_id' => $value['activity_id'], 'user_id' => $value['user_id']])->field('name, phone, customer_type')->find();

                $excelData[$key] = [
                    $value['prize_sn'] ?? '', $value['nickname'] ?? '', $value['openid'] ?? '', $value['order_info']['name'] ?? '', $value['order_info']['phone'] ?? '', $value['order_info']['customer_type'] ?? '',
                    $value['create_time'] ?? '', $value['prize_name'] ?? '', ($value['receive_status'] == 0 ? '未领取' : '已领取'), ($value['status'] == 0 ? '未核销' : ($value['status'] == 1 ? '已作废' : '已核销')),
                    $value['activity_title'] ?? '', $value['staff_nickname'] ?? '',
                ];
            }
            $spreadsheet = excel::handleExcel([[
                'name' => '翻牌抽奖',
                'title' => [
                    '中奖编号', '昵称', 'OPENID', '姓名', '手机号', '地址',
                    '中奖时间', '中奖奖品', '领取状态', '核销状态',
                    '所属活动', '所属商家'
                ],
                'data' => $excelData ?? []
            ]], []);
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');

            $file_name = '翻牌抽奖';
            $file_path = runtime_path() . '/excel/' . $file_name . time() . '.' . mt_rand(100000, 999999) . '.xlsx';
            // 保存文件到 public 下
            @mkdir(runtime_path() . '/excel/');
            $writer->save($file_path);
            // 下载文件
            return response()->download($file_path, $file_name . '.xlsx');
        } catch (\Exception|\PhpOffice\PhpSpreadsheet\Exception$e) {
            return $this->error($e->getMessage());
        }
    }
}
